import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { AppModule } from '../src/app.module';

describe('Auth Exceptions (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  describe('/auth/login (POST)', () => {
    it('应该返回400状态码当用户名或密码为空时', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({})
        .expect(400)
        .expect((res) => {
          expect(res.body.code).toBe('PARAMETER_ERROR');
          expect(res.body.message).toContain('用户名和密码不能为空');
        });
    });

    it('应该返回400状态码当用户名不存在时', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({
          username: 'nonexistentuser',
          password: 'password123',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.code).toBe('INVALID_CREDENTIALS');
          expect(res.body.message).toBe('用户名或密码错误');
        });
    });

    it('应该返回400状态码当密码错误时', () => {
      return request(app.getHttpServer())
        .post('/auth/login')
        .send({
          username: 'admin', // 假设存在admin用户
          password: 'wrongpassword',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.code).toBe('INVALID_CREDENTIALS');
          expect(res.body.message).toBe('用户名或密码错误');
        });
    });
  });

  describe('/auth/refresh (POST)', () => {
    it('应该返回400状态码当刷新令牌为空时', () => {
      return request(app.getHttpServer())
        .post('/auth/refresh')
        .send({})
        .expect(400)
        .expect((res) => {
          expect(res.body.code).toBe('PARAMETER_ERROR');
          expect(res.body.message).toContain('刷新令牌不能为空');
        });
    });

    it('应该返回400状态码当刷新令牌格式错误时', () => {
      return request(app.getHttpServer())
        .post('/auth/refresh')
        .send({
          refreshToken: 'invalid-token-format',
        })
        .expect(400)
        .expect((res) => {
          expect(res.body.code).toBe('TOKEN_VERIFICATION_ERROR');
          expect(res.body.message).toContain('令牌验证失败');
        });
    });
  });
});
